package com.ruoyi.project.rest.order.service.impl;

import com.ruoyi.common.constant.OrderStateConstants;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.common.utils.uuid.Seq;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.rest.detail.domain.RestOrderDetail;
import com.ruoyi.project.rest.detail.mapper.RestOrderDetailMapper;
import com.ruoyi.project.rest.goods.domain.RestGoods;
import com.ruoyi.project.rest.goods.mapper.RestGoodsMapper;
import com.ruoyi.project.rest.member.domain.RestMember;
import com.ruoyi.project.rest.member.service.IRestMemberService;
import com.ruoyi.project.rest.order.domain.OrderPay;
import com.ruoyi.project.rest.order.domain.RestOrder;
import com.ruoyi.project.rest.order.domain.RestOrderDto;
import com.ruoyi.project.rest.order.mapper.RestOrderMapper;
import com.ruoyi.project.rest.order.service.IRestOrderService;
import com.ruoyi.project.rest.statistics.domain.RestStatisticsData;
import com.ruoyi.project.rest.trade.domain.RestMemberTrade;
import com.ruoyi.project.rest.trade.service.IRestMemberTradeService;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * 订单Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-28
 */
@Service
public class RestOrderServiceImpl implements IRestOrderService {
    @Autowired
    private RestOrderMapper restOrderMapper;
    @Autowired
    private RestGoodsMapper restGoodsMapper;
    @Autowired
    private RestOrderDetailMapper restOrderDetailMapper;
    @Autowired
    private IRestMemberService restMemberService;
    @Autowired
    private IRestMemberTradeService restMemberTradeService;

    /**
     * 查询订单
     *
     * @param orderNo 订单主键
     * @return 订单
     */
    @Override
    public RestOrder selectRestOrderByOrderNo(String orderNo) {
        return restOrderMapper.selectRestOrderByOrderNo(orderNo);
    }

    /**
     * 查询订单列表
     *
     * @param restOrder 订单
     * @return 订单
     */
    @Override
    public List<RestOrder> selectRestOrderList(RestOrder restOrder) {
        return restOrderMapper.selectRestOrderList(restOrder);
    }

    /**
     * 新增订单
     *
     * @param restOrder 订单
     * @return 结果
     */
    @Override
    public int insertRestOrder(RestOrderDto restOrder) {
        return restOrderMapper.insertRestOrder(restOrder);
    }

    /**
     * 修改订单
     *
     * @param restOrder 订单
     * @return 结果
     */
    @Override
    public int updateRestOrder(RestOrder restOrder) {
        return restOrderMapper.updateRestOrder(restOrder);
    }

    /**
     * 批量删除订单
     *
     * @param orderNos 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteRestOrderByOrderNos(String orderNos) {
        return restOrderMapper.deleteRestOrderByOrderNos(Convert.toStrArray(orderNos));
    }

    /**
     * 删除订单信息
     *
     * @param orderNo 订单主键
     * @return 结果
     */
    @Override
    public int deleteRestOrderByOrderNo(String orderNo) {
        return restOrderMapper.deleteRestOrderByOrderNo(orderNo);
    }

    @Override
    @Transactional
    public int save(RestOrderDto restOrder) {
        BigDecimal money = BigDecimal.ZERO;
        int i = 0;
        if (StringUtils.isEmpty(restOrder.getOrderNo())) {
            restOrder.setOrderNo("DD" + Seq.getId());
            restOrder.setState(OrderStateConstants.CREATE);
            restOrder.setCreateTime(DateUtils.getNowDate());
            restOrder.setCreateBy(ShiroUtils.getSysUser().getUserName());
            i = insertRestOrder(restOrder);
        } else {
            i = updateRestOrder(restOrder);
        }
        if (i > 0) {
            restOrderDetailMapper.deleteRestOrderDetailByOrderNo(restOrder.getOrderNo());
            for (Map<String, Object> map : restOrder.getGoodsList()) {
                RestGoods goods = restGoodsMapper.selectRestGoodsById(Long.valueOf(map.get("goodsId").toString()));
                RestOrderDetail detail = new RestOrderDetail();
                detail.setGoodsId(goods.getId());
                detail.setGoodsName(goods.getGoodsName());
                detail.setGoodsMoney(goods.getMoney());
                detail.setGoodsUrl(goods.getGoodsUrl());
                detail.setOrderNo(restOrder.getOrderNo());
                detail.setGoodsNum(Long.valueOf(map.get("goodsNum").toString()));
                restOrderDetailMapper.insertRestOrderDetail(detail);
                money = money.add(detail.getGoodsMoney().multiply(new BigDecimal(detail.getGoodsNum())));
            }
            restOrder.setMoney(money);
            updateRestOrder(restOrder);
        }
        return i;
    }

    @Override
    @Transactional
    public AjaxResult orderPay(OrderPay orderPay) {
        RestOrder restOrder = restOrderMapper.selectRestOrderByOrderNo(orderPay.getOrderNo());
        if (restOrder == null) {
            return AjaxResult.error("订单不存在！");
        }
        if (restOrder.getState().equals(401)) {
            return AjaxResult.success("订单已经支付");
        }
        if (StringUtils.isNotEmpty(orderPay.getPhone())) {
            RestMember restMember = restMemberService.selectRestMemberByPhone(orderPay.getPhone());
            if (restMember == null) {
                return AjaxResult.error("会员不存在");
            }
            if (restMember.getBalance().compareTo(orderPay.getPayMoney()) == -1) {
                return AjaxResult.error("会员余额不足");
            }
            RestMemberTrade trade = new RestMemberTrade();
            trade.setType(102);
            trade.setMemberNo(restMember.getMemberNo());
            trade.setBeforeMoney(restMember.getBalance());
            trade.setMoney(orderPay.getPayMoney());
            trade.setAfterMoney(restMember.getBalance().subtract(orderPay.getPayMoney()));
            trade.setOrderNo(orderPay.getOrderNo());
            restMemberTradeService.insertRestMemberTrade(trade);

            RestMember upMember = new RestMember();
            upMember.setId(restMember.getId());
            upMember.setBalance(restMember.getBalance().subtract(orderPay.getPayMoney()));
            restMemberService.updateRestMember(upMember);
        }
        RestOrder order = new RestOrder();
        order.setOrderNo(orderPay.getOrderNo());
        order.setPayMoney(orderPay.getPayMoney());
        order.setState(OrderStateConstants.PAY);
        int i = restOrderMapper.updateRestOrder(order);
        if (i == 0) {
            throw new BaseException("结算失败！请重新结算");
        }
        return AjaxResult.success();
    }

    @Override
    public List<RestStatisticsData> selectStatisticsQuery(String startTime, String endTime) {
        return restOrderMapper.selectStatisticsQuery(startTime,endTime);
    }
}
